package com.jfirer.redisserver;

import com.jfirer.baseutil.TRACEID;
import com.jfirer.jnet.common.api.ProcessorContext;
import com.jfirer.jnet.common.buffer.BufferAllocator;
import com.jfirer.jnet.common.decoder.AbstractDecoder;
import com.jfirer.redisserver.command.Command;
import com.jfirer.redisserver.command.CommandFactory;
import com.jfirer.redisserver.resp.BulkString;
import com.jfirer.redisserver.resp.Errors;
import com.jfirer.redisserver.resp.Resp;
import com.jfirer.redisserver.resp.RespArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CommandDecoder extends AbstractDecoder
{
    private static final Logger LOGGER = LoggerFactory.getLogger(CommandDecoder.class);

    public CommandDecoder(BufferAllocator allocator)
    {
        super(allocator);
    }

    @Override
    protected void process0(ProcessorContext ctx)
    {
        TRACEID.newTraceId();
        while (accumulation.remainRead() != 0)
        {
            int mark = accumulation.getReadPosi();
            try
            {
                Resp resp = Resp.decode(accumulation);
                if (resp instanceof RespArray == false)
                {
                    throw new IllegalStateException("客户端发送的命令应该只能是Resp Array 类型");
                }
                Command command = CommandFactory.from((RespArray) resp);
                if (command == null)
                {
                    ctx.fireWrite(new Errors("unsupport command:" + ((BulkString) ((RespArray) resp).getArray()[0]).getContent().toUtf8String()));
                }
                else
                {
                    ctx.fireRead(command);
                }
            }
            catch (Exception e)
            {
                accumulation.setReadPosi(mark);
                break;
            }
        }
    }

    @Override
    public void prepareFirstRead(ProcessorContext ctx)
    {
        String traceId = TRACEID.newTraceId();
        LOGGER.debug("traceId:{} 有新的客户端接入", traceId);
    }
}
